package stdio.costa.imoca.task;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import stdio.costa.imoca.card.PostcardPreviewBuilder;
import stdio.costa.imoca.model.Postcard;
import stdio.costa.imoca.model.Preview;

@Service
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class AsyncPostcardMaker implements PostcardMaker {

	private static final Logger logger = LoggerFactory.getLogger(AsyncPostcardMaker.class);
	
	@PersistenceContext
	private EntityManager entityManager; 
	
	@Transactional
	@Async
	@Override
	public void make(Postcard postcard) {
		try {
			logger.info("Building preview for postcard {}", postcard.getUuid());
			Preview preview = new PostcardPreviewBuilder(postcard).build();
			entityManager.persist(preview);
			postcard.setPreview(preview);
			postcard.clearLocalStorage();
			entityManager.merge(postcard);
		} catch (Exception e) {
			logger.error("Failed to build postcard preview", e);
		}
	}

}
